import React, {memo, useState, useEffect, useRef} from 'react'
import {
	Button,
	Form,
	Row,
	Col,
	Input,
	Select,
	DatePicker,
	message,
	Tabs,
} from 'antd'
import moment from 'moment'
import {history} from 'umi'
import styles from './index.less'
import {taskStart} from '../dict'
import Inventlist from './inventList'
import AccessoryList from './accessoryList'
import {
	taskUpdate,
	getTaskList,
	getTaskAccessory,
} from '@/service/storage/inventoryTask'
import {getPublicDownloadUrl} from '@/service/common/upload'
import OperationRecord from '@/components/OperationRecord'

const Index = memo((props: {location: any}) => {
	const [page, setPage] = useState({
		current: 1,
		size: 10,
	})
	const accessoryListRef = useRef<any>(null)
	const [basicData] = Form.useForm<any>()
	const [accessoryList, setAccessoryList] = useState<any>([]) // 附件列表

	const {query} = props.location
	const statusType = query.statusType === 'detail'
	const getNowData = (params: {id: any}) => {
		getTaskList({...params, ...page})
			.then((res: any) => {
				if (res?.success) {
					const obj = res?.data?.page?.records[0]
					const nowData = {
						id: obj.id,
						type: obj.type,
						description: obj.description,
						createUserName: obj.createUserName,
						supervisorName: obj.supervisorName,
						stockmanName: obj.stockmanName,
						status: obj.status,
						beginTime: obj.beginTime ? moment(obj.beginTime) : '',
						endTime: obj.endTime ? moment(obj.endTime) : '',
					}
					basicData.setFieldsValue({...nowData})
				}
			})
			.catch((error) => {
				message.error(error)
			})
	}
	const getNowAccessory = (params: {taskId: any}) => {
		getTaskAccessory({...params})
			.then((res) => {
				if (res?.success) {
					// 附件示例url
					const planUrls = res?.data.map((item: any) => item.planUrl)
					// 上传文件url
					const urls = res?.data.map((item: any) => item.url)
					if (planUrls?.length) {
						getPublicDownloadUrl(planUrls).then((result: any) => {
							if (result?.success) {
								const newList = [...res.data]
								newList?.forEach(
									(item: {planUrl: any}, index) => {
										const urlData = result?.data?.find(
											(items: {id: number}) =>
												items?.id ===
												Number(item?.planUrl),
										)
										if (urlData) {
											res.data[index].planhref =
												urlData?.url
											res.data[index].planUrlName =
												urlData?.filename
										}
									},
								)
							}
						})
					}
					if (urls?.length) {
						getPublicDownloadUrl(urls).then((result: any) => {
							if (result?.success) {
								const newList = [...res.data]
								newList?.forEach((item: {url: any}, index) => {
									const urlData = result?.data?.find(
										(items: {id: number}) =>
											items?.id === Number(item?.url),
									)
									if (urlData) {
										res.data[index].href = urlData?.url
										res.data[index].urlName =
											urlData?.filename
									}
								})
							}
						})
					}
					setAccessoryList(res?.data)
				}
			})
			.catch((error) => {
				message.error(error)
			})
	}
	useEffect(() => {
		if (query?.id) {
			getNowData({id: query.id})
			getNowAccessory({taskId: query.id})
		}
	}, [query?.id])
	const onSubmit = async (types: any) => {
		if (types === 1) {
			const params = await basicData.validateFields()
			let accessoryData: any
			if (accessoryListRef?.current) {
				accessoryData = await accessoryListRef?.current?.getData()
			}
			let newData: any = {}
			if (params) {
				newData = {
					...params,
					taskId: params.id,
					beginTime: moment(params?.beginTime).format(
						'YYYY-MM-DD HH:mm:ss',
					),
					endTime: moment(params?.endTime).format(
						'YYYY-MM-DD HH:mm:ss',
					),
				}
				if (accessoryData) {
					newData.planAnnexList = accessoryData?.map(
						(item: {taskAnnexId: any; url: number}) => ({
							taskAnnexId: item?.taskAnnexId,
							url: item?.url,
						}),
					)
				}
				taskUpdate({...newData})
					.then((res: any) => {
						if (res?.success) {
							message.success('保存成功！')
							history.push({
								pathname:
									'/storage/assetInventory/inventoryTask',
							})
						}
					})
					.catch((error) => {
						message.error(error)
					})
			}
		} else if (types === 2) {
			history.push({
				pathname: '/storage/assetInventory/inventoryTask',
			})
		}
	}
	return (
		<div className={styles.add}>
			<div className={styles.title}>基本信息</div>
			<Form
				form={basicData}
				name="basic"
				layout="horizontal"
				labelCol={{flex: '160px'}}
				labelAlign="right"
				labelWrap
				autoComplete="off"
				disabled>
				<Row gutter={12}>
					<Col sm={{span: 24}} md={{span: 12}} lg={{span: 8}}>
						<Form.Item
							label="任务类型"
							name="type"
							// rules={[{ required: true }]}
						>
							<Select
								placeholder="请选择"
								fieldNames={{value: 'key', label: 'label'}}
								allowClear
								disabled
								// value={}
								options={[
									{key: 1, label: '全盘'},
									{key: 2, label: '抽盘'},
								]}
							/>
						</Form.Item>
					</Col>
					<Col sm={{span: 24}} md={{span: 12}} lg={{span: 8}}>
						<Form.Item
							label="任务编号"
							name="id"
							// rules={[{ required: true }]}
						>
							<Input placeholder="请输入" disabled />
						</Form.Item>
					</Col>
					<Col sm={{span: 24}} md={{span: 12}} lg={{span: 8}}>
						<Form.Item
							label="任务分配人"
							name="createUserName"
							// rules={[{ required: true }]}
						>
							<Input placeholder="请输入" disabled />
						</Form.Item>
					</Col>
				</Row>
				<Row gutter={12}>
					<Col sm={{span: 24}} md={{span: 12}} lg={{span: 8}}>
						<Form.Item
							label="任务开始时间"
							name="beginTime"
							// rules={[{ required: true }]}
						>
							<DatePicker
								placeholder="请选择"
								format="YYYY-MM-DD HH:mm:ss"
								disabled
							/>
						</Form.Item>
					</Col>
					<Col sm={{span: 24}} md={{span: 12}} lg={{span: 8}}>
						<Form.Item
							label="任务结束时间"
							name="endTime"
							// rules={[{ required: true }]}
						>
							<DatePicker
								placeholder="请选择"
								format="YYYY-MM-DD HH:mm:ss"
								disabled
							/>
						</Form.Item>
					</Col>
					<Col span={24}>
						<Form.Item
							label="任务要求描述"
							name="description"
							// rules={[{ required: true }]}
						>
							<Input.TextArea
								maxLength={100}
								placeholder="请输入（最多100个字）"
								disabled
								//    autoSize={{ minRows: 4, maxRows: 5 }}
							/>
						</Form.Item>
					</Col>
				</Row>
				<Row gutter={12}>
					<Col sm={{span: 24}} md={{span: 12}} lg={{span: 6}}>
						<Form.Item
							label="盘点人"
							name="stockmanName"
							rules={[{required: true}]}>
							<Input placeholder="请输入" disabled={statusType} />
						</Form.Item>
					</Col>
					<Col sm={{span: 24}} md={{span: 12}} lg={{span: 6}}>
						<Form.Item
							label="监盘人"
							name="supervisorName"
							rules={[{required: true}]}>
							<Input placeholder="请输入" disabled={statusType} />
						</Form.Item>
					</Col>
					<Col sm={{span: 24}} md={{span: 12}} lg={{span: 8}}>
						<Form.Item
							label="任务状态"
							name="status"
							rules={[{required: true}]}>
							<Select
								placeholder="请选择"
								// onChange={(e) => isChangeType(e)}
								fieldNames={{value: 'key', label: 'label'}}
								allowClear
								disabled={statusType}
								options={[...taskStart]}
							/>
						</Form.Item>
					</Col>
				</Row>
			</Form>

			<Tabs
				defaultActiveKey="1"
				type="card"
				items={[
					{
						label: '盘点表',
						key: '1',
						children: (
							<Inventlist
								taskId={query.id}
								status={statusType}
								page={page}
								setPage={setPage}
							/>
						),
					},
					{
						label: '盘点反馈附件',
						key: ' 2',
						children: (
							<AccessoryList
								ref={accessoryListRef}
								data={accessoryList}
								status={statusType}
							/>
						),
					},
					{
						label: '操作记录',
						key: '3',
						children: (
							<OperationRecord
								businessId={query?.id}
								businessType={26}
							/>
						),
					},
				]}
			/>
			{statusType ? (
				<div className={styles.btn} style={{marginTop: 80}}>
					<Button
						onClick={() => onSubmit(2)}
						style={{margin: '0 8px'}}>
						关闭
					</Button>
				</div>
			) : (
				<div className={styles.btn} style={{marginTop: 80}}>
					<Button
						type="primary"
						htmlType="submit"
						onClick={() => onSubmit(1)}>
						保存
					</Button>
					<Button
						onClick={() => onSubmit(2)}
						style={{margin: '0 8px'}}>
						关闭
					</Button>
				</div>
			)}
		</div>
	)
})

export default Index
